import 'package:dio/dio.dart';
import 'package:playtruly/common/services/http.dart';
import 'package:playtruly/common/models/index.dart';
import 'package:playtruly/common/utils/encryption_util.dart';
import 'dart:developer' as developer;

/// 首页相关API
class HomeApi {
  /// 获取首页附近商家和评论信息
  /// [latitude] 纬度
  /// [longitude] 经度
  /// [shopLimit] 商铺显示数量，默认10
  /// [page] 页码，默认1
  /// [userId] 用户ID（用于检查点赞状态）
  /// [category] 分类筛选
  /// 返回HomeNearbyResponse对象
  static Future<HomeNearbyResponse> getNearbyShopsAndComments({
    required double latitude,
    required double longitude,
    int? shopLimit,
    int? page,
    int? userId,
    List<String>? category,
  }) async {
    try {
      print('🔥🔥🔥 =============== 首页API调试开始（已恢复经纬度）===============');
      print('📍 请求坐标: ($latitude, $longitude)');
      print('📄 页码: ${page ?? 1}');
      print('🏪 商铺限制: ${shopLimit ?? 10}');
      print('👤 用户ID: $userId');
      print('🏷️ 分类筛选: $category');
      
      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000);
      print('⏰ 生成时间戳: $timestamp');
      
      // 🔥 恢复经纬度参数（服务器必需）
      final requestData = {
        'longitude': longitude.toString(),  // 🔑 String类型坐标（必需）
        'latitude': latitude.toString(),    // 🔑 String类型坐标（必需）
        'limit': null,                      // 🔑 null值（与Android一致）
        'page': page ?? 1,                  // 🔑 int类型页码
        'Category': category ?? <String>[], // 🔑 大写C，空数组
        'userId': userId?.toString() ?? '0', // 🔑 String类型用户ID，如果未传递则为'0'
        'timestamp': timestamp,             // 🔑 int类型时间戳
      };
      
      print('🔥🔥🔥 首页请求参数（加密前）: $requestData');
      print('✅ 已恢复经纬度参数，服务器要求必需');
      
      // 使用AES加密请求数据
      print('🔐 开始AES加密首页数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      print('🔒 首页加密完成，载荷长度: ${encryptedPayload.toString().length}');
      print('🔒 加密数据预览: ${encryptedPayload.toString().substring(0, 100)}...');

      // 发送加密请求
      print('🚀 发送首页API请求到: /index/nearby/');
      final response = await HttpService.to.post(
        '/index/nearby/',
        data: encryptedPayload,
      );

      print('🔥🔥🔥 首页API响应: $response');
      
      // 解析响应为HomeNearbyResponse对象
      final homeResponse = HomeNearbyResponse.fromJson(response);
      
      print('✅ 首页响应解析完成 - 状态: ${homeResponse.status}');
      print('🏪 商店数量: ${homeResponse.dataShop.length}');
      print('💬 评论数量: ${homeResponse.dataComment != null ? 1 : 0}');
      print('🔥🔥🔥 =============== 首页API调试结束（已恢复经纬度）===============');
      print('📊 测试结果: ${homeResponse.dataShop.length > 0 || homeResponse.dataComment != null ? "✅ 有数据" : "❌ 仍无数据"}');

      return homeResponse;
      
    } catch (e, stackTrace) {
      print('💥 🔥首页API异常: $e');
      print('📚 异常堆栈: $stackTrace');
      
      // 返回失败响应
      return HomeNearbyResponse(
        status: 'error',
        message: '获取首页附近信息失败: ${e.toString()}',
        dataComment: null,
        dataShop: [],
      );
    }
  }

  /// 获取首页轮播图数据
  static Future<List<String>> getBanners() async {
    try {
      developer.log('🔄 开始获取首页轮播图...');
      
      // 这里可以添加轮播图API调用
      // 目前返回模拟数据
      final banners = [
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_154f5afcc73ab7814a745378c6dd2846_edit_391954352758421.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_06409c288f6c65c4f600bddf9283602f_edit_391871265051142.png",
        "https://bai-ying.oss-cn-qingdao.aliyuncs.com/image/art_works/share_0e5b4a2b28ed3de4b0bd82dbf7c6903d_edit_391867197811038.png",
      ];
      
      developer.log('✅ 轮播图获取成功: ${banners.length}张');
      return banners;
      
    } catch (e) {
      developer.log('❌ 获取轮播图失败: $e');
      return [];
    }
  }

  /// 点赞评论
  /// [commentId] 评论ID
  /// [userId] 用户ID
  /// [isLike] 是否点赞（true=点赞，false=取消点赞）
  static Future<bool> likeComment({
    required int commentId,
    required int userId,
    required bool isLike,
  }) async {
    try {
      developer.log('🔄 开始${isLike ? "点赞" : "取消点赞"}评论...');
      developer.log('💬 评论ID: $commentId');
      developer.log('👤 用户ID: $userId');
      
      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
      
      // 构建请求数据
      final requestData = {
        'commentId': commentId,
        'userId': userId,
        'action': isLike ? 'like' : 'unlike',
        'timestamp': timestamp,
      };
      
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 使用AES加密请求数据
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送加密请求 - 这里使用假设的评论点赞API
      final response = await HttpService.to.post(
        '/comments/like/',
        data: encryptedPayload,
      );

      developer.log('✅ 评论点赞响应: $response');
      
      // 检查响应状态
      final status = response['status'] as String?;
      final success = status == 'success';
      
      developer.log('📈 点赞结果: ${success ? "成功" : "失败"}');
      
      return success;
      
    } catch (e) {
      developer.log('❌ 评论点赞失败: $e');
      return false;
    }
  }

  /// 商店打卡
  /// [userId] 用户ID
  /// [shopId] 商店ID
  /// [action] 操作类型 ("check_in" 或 "cancel")
  static Future<Map<String, dynamic>?> checkInShop({
    required int userId,
    required int shopId,
    required String action,
  }) async {
    try {
      developer.log('🔄 开始商店打卡操作...');
      developer.log('👤 用户ID: $userId');
      developer.log('🏪 商店ID: $shopId');
      developer.log('⚡ 操作: $action');
      
      // 生成时间戳
      final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
      
      // 构建请求数据
      final requestData = {
        'userId': userId,
        'shopId': shopId,
        'action': action,
        'timestamp': timestamp,
      };
      
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 使用AES加密请求数据
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      // 发送加密请求
      final response = await HttpService.to.post(
        '/shop/check-in/',
        data: encryptedPayload,
      );

      developer.log('✅ 商店打卡响应: $response');
      
      return response;
      
    } catch (e) {
      developer.log('❌ 商店打卡失败: $e');
      return null;
    }
  }
}
